package xyz.thoughtset.viewer.common.log.listener;

import cn.hutool.core.convert.Convert;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import xyz.thoughtset.viewer.common.core.entity.IdMeta;
import xyz.thoughtset.viewer.common.envvar.service.EnvVarsService;
import xyz.thoughtset.viewer.common.log.constant.LogInfoExConstant;
import xyz.thoughtset.viewer.common.log.entity.LogInfo;
import xyz.thoughtset.viewer.common.log.entity.event.LogMsgEvent;
import xyz.thoughtset.viewer.common.log.service.LogInfoService;

@Slf4j
@Component
public class LogInfoListener  implements ApplicationListener<LogMsgEvent> {
    @Autowired
    private LogInfoService excInfoService;
    @Autowired
    private EnvVarsService envVarsService;
    @Autowired
    private ObjectMapper objectMapper;


    @Async(LogInfoExConstant.EX_NAME)
    @Override
    public void onApplicationEvent(LogMsgEvent event) {
        LogInfo logInfo = new LogInfo();
        Object data = event.getData();
        logInfo.setActive(event.getActive());
        logInfo.setType(event.getSubject());
        if (data != null) {
            if (data instanceof IdMeta){
                logInfo.setPid(((IdMeta)data).getId());
            }
            if (data.getClass().isPrimitive()||String.class.equals(data.getClass())){
                logInfo.setData(Convert.convert(String.class,data));
            }else{
                try {
                    String jsonData = objectMapper.writeValueAsString(data);
                    logInfo.setData(jsonData);
                } catch (Exception e) {
                    log.error("LogInfoListener error: {}", e.getMessage(), e);
                }
            }
        }
        excInfoService.save(logInfo);

    }
}
